package com.zzyl.nursing.service.impl;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeParseException;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.dto.CheckInConfigDto;
import com.zzyl.nursing.dto.CheckInElderDto;
import com.zzyl.nursing.dto.ElderFamilyDto;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.util.CodeGenerator;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

/**
 * 入住Service业务层处理
 *
 * @author li13
 * @date 2025-09-30
 */
@Service
@Slf4j
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService {
    @Autowired
    private CheckInMapper checkInMapper;
    @Autowired
    private ElderMapper elderMapper;

    @Autowired
    private BedMapper bedMapper;

    @Autowired
    private CheckInConfigMapper checkInConfigMapper;

    @Autowired
    private ContractMapper contractMapper;

    /**
     * 查询入住
     *
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id) {
        return checkInMapper.selectById(id);
    }

    /**
     * 查询入住列表
     *nursing_task
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn) {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn) {
        return checkInMapper.insert(checkIn);
    }

    /**
     * 修改入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn) {
        return checkInMapper.updateById(checkIn);
    }

    /**
     * 批量删除入住
     *
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids) {
        return checkInMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除入住信息
     *
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id) {
        return checkInMapper.deleteById(id);
    }

    /**
     * 入住申请
     *
     * @param dto
     */
    @Override
    @Transactional
    public void addApply(CheckInApplyDto dto) {
        //校验老人是否已经入住
        LambdaQueryWrapper<Elder> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Elder::getIdCardNo, dto.getCheckInElderDto().getIdCardNo());
        wrapper.eq(Elder::getStatus, 1);
        Elder elder = elderMapper.selectOne(wrapper);
        if (elder != null) {
            throw new BaseException("该老人已经入住");
        }
        //更新床位状态
        Bed bed = bedMapper.selectById(dto.getCheckInConfigDto().getBedId());
        bed.setBedStatus(1);
        //更新数据库中该床位的信息
        bedMapper.updateById(bed);
        //插入入住老人信息
        elder = insertOrUpdate(bed, dto.getCheckInElderDto());
        //新增合同
        insertContract(dto, elder);
        //新增入住信息
        CheckIn checkIn=saveCheckIn(dto, elder, bed);
        //新增入住配置
        saveCheckInConfig(dto.getCheckInConfigDto(), checkIn);
    }



    /**
     * 新增入住配置
     *
     * @param checkInConfigDto
     * @param checkIn
     */
    private void saveCheckInConfig(CheckInConfigDto checkInConfigDto, CheckIn checkIn) {
        CheckInConfig checkInConfig = new CheckInConfig();
        BeanUtils.copyProperties(checkInConfigDto, checkInConfig);
        //设置入住配置信息
        checkInConfig.setCheckInId(checkIn.getId());

        checkInConfigMapper.insert(checkInConfig);
    }

    /**
     * 新增入住信息
     *
     * @param dto
     * @param elder
     * @param bed
     */
    private CheckIn saveCheckIn(CheckInApplyDto dto, Elder elder, Bed bed) {
        CheckIn checkIn = new CheckIn();
        //设置老人信息
        checkIn.setElderId(elder.getId());
        checkIn.setElderName(elder.getName());
        checkIn.setIdCardNo(elder.getIdCardNo());
        //设置入住信息
        checkIn.setStartDate(dto.getCheckInConfigDto().getStartDate());
        checkIn.setEndDate(dto.getCheckInConfigDto().getEndDate());
        checkIn.setNursingLevelName(dto.getCheckInConfigDto().getNursingLevelName());
        checkIn.setBedNumber(bed.getBedNumber());
        //设置老人家属
        List<ElderFamilyDto> elderFamilyDtos = dto.getElderFamilyDtoList();
        checkIn.setRemark(JSON.toJSONString(elderFamilyDtos));
        //新增入住信息
        checkInMapper.insert(checkIn);
        return checkIn;
    }

    /**
     * 新增合同
     *
     * @param dto
     * @param elder
     */

    private void insertContract(CheckInApplyDto dto, Elder elder) {
        Contract contract = new Contract();
        BeanUtils.copyProperties(dto.getCheckInContractDto(), contract);
        //设置合同信息
        contract.setElderId(elder.getId().intValue());
        contract.setElderName(elder.getName());
        contract.setStartDate(dto.getCheckInConfigDto().getStartDate());
        contract.setEndDate(dto.getCheckInConfigDto().getEndDate());
        if (LocalDateTime.now().isAfter(contract.getStartDate())) {
            contract.setStatus(1);
        }
        //设置合同编号
        contract.setContractNumber("HT" + CodeGenerator.generateContractNumber());
        //新增合同
        contractMapper.insert(contract);
    }

    /**
     * 新增或更新入住老人信息
     *
     * @param bed
     * @param checkInElderDto
     * @return
     */
    private Elder insertOrUpdate(Bed bed, CheckInElderDto checkInElderDto) {
        //因为要更新
        Elder elder = new Elder();
        BeanUtils.copyProperties(checkInElderDto, elder);
        elder.setBedId(bed.getId());
        elder.setBedNumber(bed.getBedNumber());

        //查老人信息
        Elder elderDb = elderMapper.selectOne(new LambdaQueryWrapper<Elder>().eq(Elder::getIdCardNo, checkInElderDto.getIdCardNo()));
        if (elderDb != null) {
            //如果存在就更新
            //设置老人id
            elder.setId(elderDb.getId());
            elderMapper.updateById(elder);
        } else {
            //否则就插入
            elderMapper.insert(elder);
        }
        return elder;
    }

    /**
     * 获取入住详情
     *
     * @param id
     * @return
     */
    @Override
    public CheckInDetailVo detail(Long id) {
        CheckInDetailVo detailVo = new CheckInDetailVo();
        // 1. 查询入住记录（基础信息）
        CheckIn checkIn = checkInMapper.selectById(id);
        if (checkIn == null) {
            throw new BaseException("入住记录不存在");
        }
        // 2. 查询老人信息并转换为CheckInElderVo
        if (checkIn.getElderId() != null) {
            Elder elder = elderMapper.selectById(checkIn.getElderId());
            if (elder != null) {
                CheckInElderVo elderVo = new CheckInElderVo();
                BeanUtils.copyProperties(elder, elderVo);
                // 补充计算年龄
                if (StringUtils.isNotEmpty(elderVo.getBirthday())) {
                    try {
                        LocalDate birthDate = LocalDate.parse(elderVo.getBirthday());
                        LocalDate now = LocalDate.now();
                        elderVo.setAge((int) ChronoUnit.YEARS.between(birthDate, now));
                    } catch (DateTimeParseException e) {
                        log.error("日期格式转换错误：{}", elderVo.getBirthday(), e);
                        elderVo.setAge(null);
                    }
                }
                detailVo.setCheckInElderVo(elderVo);
            }
        }

        // 3. 解析家属信息
        List<ElderFamilyVo> familyVoList = new ArrayList<>();
        String familyJson = checkIn.getRemark();
        if (StringUtils.isNotEmpty(familyJson)) {
            try {
                List<ElderFamilyDto> familyDtoList = JSON.parseArray(familyJson, ElderFamilyDto.class);
                familyVoList = familyDtoList.stream()
                        .map(dto -> {
                            ElderFamilyVo vo = new ElderFamilyVo();
                            BeanUtils.copyProperties(dto, vo);
                            return vo;
                        })
                        .collect(Collectors.toList());
            } catch (Exception e) {
                log.warn("解析家属信息失败: {}", familyJson, e);
            }
        }
        detailVo.setElderFamilyVoList(familyVoList);

        // 4. 查询合同信息（补充时间排序，避免多合同场景）
        if (checkIn.getElderId() != null) {
            Contract contract = contractMapper.selectOne(
                    new LambdaQueryWrapper<Contract>()
                            .eq(Contract::getElderId, checkIn.getElderId())
                            .orderByDesc(Contract::getCreateTime)
                            .last("LIMIT 1")
            );
            detailVo.setContract(contract);
        }

        // 5. 查询入住配置
        CheckInConfig config = checkInConfigMapper.selectOne(
                new LambdaQueryWrapper<CheckInConfig>()
                        .eq(CheckInConfig::getCheckInId, id)
        );
        if (config != null) {
            CheckInConfigVo configVo = new CheckInConfigVo();
            BeanUtils.copyProperties(config, configVo);
            configVo.setStartDate(checkIn.getStartDate());
            configVo.setEndDate(checkIn.getEndDate());
            configVo.setBedNumber(checkIn.getBedNumber());
            detailVo.setCheckInConfigVo(configVo);
        }

        return detailVo;
    }
}

